<template>
	<page ref="page">
		<u-sticky>
			<!-- 吸顶进度条,只能有一个根元素 -->
			<u-line-progress v-show="showProgress" :striped="true" :percent="percent" :striped-active="true">
			</u-line-progress>
		</u-sticky>

		<u-alert-tips :show="isFailSource" type="error" :title="'无效资源'"></u-alert-tips>
		<view v-for="(item,index) of images" :class="'img_'+index" :key="'img_'+index" @click="eventViewImage(index)">
			<u-image :src="item" mode="widthFix">
				<u-loading color="#2979ff" slot="loading">
				</u-loading>
			</u-image>
		</view>
	</page>
</template>

<script>
	import page from '@/components/base-page/page.vue'
	import parser from './htmlparser/index.js'
	import downloader from './downloader/index.js'
	import resourceService from './downloader/db.js'
	export default {
		components: {
			page
		},
		data() {
			return {
				resource: null,
				images: [],
				baseUrl: 'https://www.zfl101.vip',
				percent: 0,
				showProgress: false,
				localUrls: [],
				currentIndex: 0,
				pageTop: 0,
				isFailSource: false
			}
		},
		watch: {
			currentIndex(newVal, oldVal) {
				this.scollToEl(newVal)
			}
		},
		computed: {
			localUrl() {
				return `_downloads/resources/${this.resource.id}/`
			}
		},
		onLoad(options) {
			const pageData = JSON.parse(options.index); // 字符串转对象
			if (!pageData.id) {
				pageData.id = pageData.url.substring(pageData.url.lastIndexOf('/') + 1).replace('.html', '')
			}
			uni.setNavigationBarTitle({
				title: pageData.title
			})
			this.resource = pageData;
			this.loadData();
		},
		onPageScroll(e) {
			this.pageTop = e.scrollTop;
		},
		methods: {
			updatePercent(successCount, allCount) {
				if (allCount === 0) {
					this.percent = 0;
					return 0;
				}
				this.percent = parseInt(successCount / allCount * 100)
				return this.percent;
			},
			scollToEl(index) {
				uni.createSelectorQuery().in(this).select(".img_" + index).boundingClientRect(data => {
					uni.pageScrollTo({
						scrollTop: data.top + this.pageTop,
						duration: 100
					})
				}).exec();
				// uni.createSelectorQuery().in(this).select(".item" + index).boundingClientRect(data => {  
				//       uni.pageScrollTo({  
				//         scrollTop:data.top + this.pageTop,  
				//         duration:100  
				//       })  
				//      }).exec();  
			},
			eventViewImage(index) {
				const me = this
				console.log('预览图片')
				this.currentIndex = index;
				// 预览图片
				const prev = uni.previewImage({
					current: index,
					urls: this.localUrls,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success(data) {
							me.currentIndex = data.index;
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail(err) {
							console.log(err.errMsg);
						}
					}
				});
				console.log(prev.current);
			},
			async loadData() {
				// 等待数据库打开
				await resourceService.open();
				// 判断数据库中是否存在
				const resource = await resourceService.get(this.resource.id);
				// console.log(resource)
				// console.log(`数据库查询完毕`)
				let imgUrls = []
				let successCount = 0
				let isParseOk = false
				let localUrls = []
				let titleImg = ''
				if (resource) {
					//如果存在 将 resounce 得 images 从 逗号分隔转换为 localUrl数组
					localUrls = resource.images.split(',');
					this.localUrls = localUrls;
					localUrls.forEach(localUrl => {
						//转换为平台绝对路径后，在将文件编码为 base64显示。
						downloader.getFileBase64(plus.io.convertLocalFileSystemURL(localUrl)).then(str => {
							this.images.push(str)
						})
					})
				} else {
					this.showProgress = true;
					this.$bus.pub('onresourceprogress', {
						id: this.resource.id,
						progress: 0,
						status: 4
					})
					await downloader.downloadFile(this.resource.img, this.localUrl + downloader.getFileName(this
						.resource
						.img)).then(path => {
						if (path !== '') {
							// 数据库里只存储相对路径。 _downloads/xxx/a.jpg
							titleImg = plus.io.convertAbsoluteFileSystem(path);
						}
					})
					//不存在则开始下载。
					const imgParser = new parser.detailParser(this.baseUrl + this.resource.url, allr => {
						//全部解析完成
						isParseOk = true;
					}, r => {
						if (r.resources.length === 0) {
							this.$bus.pub('onresourceprogress', {
								id: this.resource.id,
								progress: 0,
								status: 3
							})
							this.$message.toast('无效资源', 'error')
							this.isFailSource = true;
							this.showProgress = false

							return;
						}
						imgUrls = imgUrls.concat(r.resources)
						r.resources.forEach(url => {
							downloader.downloadFile(url, this.localUrl + downloader.getFileName(url))
								.then(path => {
									if (path !== '') {
										// 数据库里只存储相对路径。 _downloads/xxx/a.jpg
										localUrls.push(plus.io.convertAbsoluteFileSystem(path));
									}
									successCount++;
									const progress = this.updatePercent(successCount, imgUrls
										.length);
									this.$bus.pub('onresourceprogress', {
										id: this.resource.id,
										progress,
										status: 2
									})
									if (successCount === imgUrls.length && isParseOk) {
										//如果下载完成数量和解析数量相等，并且解析已经结束。则将资源插入数据库
										// console.log('执行数据库插入')
										resourceService.add({
											title: this.resource.title,
											id: this.resource.id,
											img: titleImg,
											images: localUrls.join(',')
										})
										this.$bus.pub('onresourceprogress', {
											id: this.resource.id,
											progress,
											status: 1
										})
										this.showProgress = false
									}
									if (path.length > 0) {
										downloader.getFileBase64(path).then(str => {
											this.images.push(str)
										})
									}
								});
						})
					});
					imgParser.parse()
				}
			}
		}
	}
</script>
